<?php
// +----------------------------------------------------------------------
// | Description: 客户
// +----------------------------------------------------------------------
// | Author: Michael_xu | gengxiaoxu@5kcrm.com
// +----------------------------------------------------------------------

namespace app\crm\controller;

use app\admin\controller\ApiCommon;
use app\admin\model\User;
use Exception;
use function Stringy\create;
use think\Hook;
use think\Request;
use think\Db;
use PHPExcel_IOFactory;

class Finance extends ApiCommon
{
    /**
     * 用于判断权限
     * @permission 无限制
     * @allow 登录用户可访问
     * @other 其他根据系统设置
     **/
    public function _initialize()
    {
        $action = [
            'permission'=>[''],//不用登录的方法
            'allow'=>['commission','flowlist']
        ];
        Hook::listen('check_auth',$action);
        $request = Request::instance();
        $a = strtolower($request->action());
        if (!in_array($a, $action['permission'])) {
            parent::_initialize();
        } else {
            $param = Request::instance()->param();
            $this->param = $param;
        }
    }

    /**
     * 财务列表
     * @author Michael_xu
     * @return
     */
    public function index()
    {
        $PersonnelModel = model('Finance');
        $param = $this->param;
        $userInfo = $this->userInfo;
        $param['user_id'] = $userInfo['id'];
        $data = $PersonnelModel->getDataList($param);
        return resultArray(['data' => $data]);
    }

    /**
     * 修改数据中心核算月份
     */
    public function update_calculate_month(){
        /*$isButler = db('admin_access')->where(["user_id"=>$this->userInfo["id"],"group_id"=>32])->find();//管家 只有管家才能有权修改
        if(!$isButler){
            return resultArray(['data' => '对不起！您没有权限，请联系管家处理！']);
        }*/
        $param = $this->param;
        $financeModel = model('Finance');
        $updateRes=$financeModel->where(["finance_id"=>$param["finance_id"]])->update(["calculate_month"=>$param["calculate_month"]]);
        return resultArray(['data' => '核算月份修改成功！']);

    }
    /**
     * 导出数据
     */
//    public function export(){
//        $PersonnelModel = model('Finance');
//        $param = $this->param;
//        $userInfo = $this->userInfo;
//        $param['user_id'] = $userInfo['id'];
//        $data = $PersonnelModel->getListDataAll($param);
//        $objPHPExcel=new \PHPExcel();
//        $phpWriter=new \PHPExcel_Writer_Excel2007($objPHPExcel);//用excel2007版式
//        $objPHPExcel->getActiveSheet()->setTitle("finance");//导出的excel名字
//        $objPHPExcel->setActiveSheetIndex(0)//开始位置，从第0行开始
//                    ->setCellValue("A1","财务编号")
//                    ->setCellValue("B1","原单编号")
//                    ->setCellValue("C1","所属部门")
//                    ->setCellValue("D1","订单类型")
//                    ->setCellValue("E1","金额")
//                    ->setCellValue("F1","退款金额")
//                    ->setCellValue("G1","追回金额")
//                    ->setCellValue("H1","业绩核算月份")
//                    ->setCellValue("I1","业绩处理方式")
//                    ->setCellValue("J1","业绩")
//                    ->setCellValue("K1","核定成本")
//                    ->setCellValue("L1","报销类型")
//                    ->setCellValue("M1","审核状态")
//                    ->setCellValue("N1","发起人")
//                    ->setCellValue("O1","创建时间")
//                    ->setCellValue("P1","审核时间")
//        ;
//        if($data){
//            $count=count($data);
//            for ($i=2;$i<=$count+1;$i++){
//                $objPHPExcel->getActiveSheet()->setCellValue("A{$i}",$data[$i-1]["order_sn"]);
//                $objPHPExcel->getActiveSheet()->setCellValue("B{$i}",$data[$i-1]["receivables_code"]);
//                $objPHPExcel->getActiveSheet()->setCellValue("C{$i}",$data[$i-1]["department"]);
//                $objPHPExcel->getActiveSheet()->setCellValue("D{$i}",$data[$i-1]["order_type"]);
//                $objPHPExcel->getActiveSheet()->setCellValue("E{$i}",$data[$i-1]["money"]);
//                $objPHPExcel->getActiveSheet()->setCellValue("F{$i}",$data[$i-1]["refund_money"]);
//                $objPHPExcel->getActiveSheet()->setCellValue("G{$i}",$data[$i-1]["recover_money"]);
//                $objPHPExcel->getActiveSheet()->setCellValue("H{$i}",$data[$i-1]["calculate_month"]);
//                $objPHPExcel->getActiveSheet()->setCellValue("I{$i}",$data[$i-1]["calculate_way"]);
//                $objPHPExcel->getActiveSheet()->setCellValue("J{$i}",$data[$i-1]["calculate"]);
//                $objPHPExcel->getActiveSheet()->setCellValue("K{$i}",$data[$i-1]["crm_oeseng"]);
//                $objPHPExcel->getActiveSheet()->setCellValue("L{$i}",$data[$i-1]["expense_type"]);
//                $objPHPExcel->getActiveSheet()->setCellValue("M{$i}",$data[$i-1]["check_status"]);
//                $objPHPExcel->getActiveSheet()->setCellValue("N{$i}",$data[$i-1]["create_user_name"]);
//                $objPHPExcel->getActiveSheet()->setCellValue("O{$i}",$data[$i-1]["created_time"]);
//                $objPHPExcel->getActiveSheet()->setCellValue("O{$i}",$data[$i-1]["check_time"]);
//            }
//        }
//        $phpWriter=\PHPExcel_IOFactory::createWriter($objPHPExcel,"Excel2007");
//        $outputFilename="finance.xls";
//        /*header("Content-Type: application/force-download");
//        header("Content-Type: application/octet-stream");
//        header("Content-Type: application/download");
//        header("Content-Type: application/vnd.ms-excel");
//        header("Content-Disposition:attachment;filename={$outputFilename}");
//        header("Content-Transfer-Encoding: binary");
//        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
//        header("Last-Modified:".gmdate("D, d M Y H:i:s"."GMT"));
//        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
//        header("Pragma: no-cache");*/
//        header("Content-Type: application/vnd.ms-excel");
//        header("Content-Disposition:attachment;filename={$outputFilename}");
//        header("Cache-Control: max-age=0");
//        $phpWriter->save("php://output");
//        exit;
//    }
    public function export(){
        $param = $this->param;
        $userInfo = $this->userInfo;
        $param['user_id'] = $userInfo['id'];
        $PersonnelModel = model('Finance');
        $list = $PersonnelModel->getListDataAll($param);
        // 导出的字段列表
        $fieldModel = new \app\admin\model\Field();
        $field_list = $fieldModel->where(["types_id"=>22])->select();
        // 文件名
        $file_name = 'finance'.date('Ymd');
        $this->exportCsv($file_name, $field_list, function($list) use ($param){
            $PersonnelModel = model('Finance');
            $list = $PersonnelModel->getListDataAll($param);
            return $list;
        });
    }
    public function exportCsv($file_name, $field_list, callback $callback)
    {
        $fieldModel = new \app\admin\model\Field();
        ini_set('memory_limit','1024M');
        set_time_limit (0);

        //调试时，先把下面这个两个header注释即可
        header("Access-Control-Expose-Headers: Content-Disposition");
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header("Content-Disposition:attachment;filename=" . $file_name . ".csv");

        header('Expires: 0');
        header('Cache-control: private');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Content-Description: File Transfer');
        header('Content-Encoding: UTF-8');
        // 加上bom头，防止用office打开时乱码
        echo "\xEF\xBB\xBF";    // UTF-8 BOM

        // 打开PHP文件句柄，php://output 表示直接输出到浏览器
        $fp = fopen('php://output', 'a');

        // 将中文标题转换编码，否则乱码
        foreach ($field_list as $i => $v) {
            $title_cell[$i] = $v['name'];
        }
        // 将标题名称通过fputcsv写到文件句柄
        fputcsv($fp, $title_cell);
        cache($file_name, $callback(0));
        // p(cache($file_name));
        foreach (cache($file_name) as $item) {
            $rows = [];
            foreach ($field_list as $rule) {
                $rows[] = $item[$rule["field"]];
            }
            fputcsv($fp, $rows);
        }
        // 将已经写到csv中的数据存储变量销毁，释放内存占用
        ob_flush();
        flush();
        fclose($fp);
        exit();
    }
}